#!/usr/bin/env python
# -*- coding: utf-8 -*-
'''
Created on 2013年11月15日

@author: iori
'''
import unittest
import shutil, os
from bencode import bdecode, bencode

class Torrent(object):
    ''' 解析种子文件结构 '''
    def __init__(self, fn=''):
        self.fn = fn
        self.schema = None
        if fn:
            self.load(fn)
        
    def load(self, fn):
        self.fn = fn
        with open(fn, 'rb') as fp:
            data = fp.read()
            self.schema = bdecode(data)
            
    def dump(self, fn=''):
        if not fn:
            fn = self.fn
        with open(fn, 'wb') as fp:
            fp.write(bencode(self.schema))     
      
    # private 用来设置种子是否为私有的。            
    @property
    def private(self):
        return self.schema['info'].get('private', 0)
    @private.setter
    def private(self, v=1):
        v = 1 if v else 0
        self.schema['info']['private'] = v
        
    def add_trackers(self, trackers=''):
        ''' 为种子添加tracker
        '''
        if not trackers:
            return
        if isinstance(trackers, (str, unicode)):
            trackers = trackers.split('\n')
        announce = self.schema.get('announce', '')
        if not announce:
            self.schema['announce'] = trackers[-1]
            trackers.pop()
        if trackers:
            announce_list = self.schema.get('announce-list', [])
            for tracker in trackers:
                announce_list.append([tracker])
            self.schema['announce-list'] = announce_list
        
class TestTorrent(unittest.TestCase):
    def setUp(self):
        self.fn = 'org.torrent'
        self.tf = 'test.torrent'
        shutil.copy(self.fn, self.tf)
       
    @unittest.skip('ok')        
    def test_set_private(self):
        t = Torrent(self.tf)
        assert t.private == 1
        t.private = 0
        t.dump()
        t = Torrent(self.tf)
        assert t.private == 0
        
    def test_add_trackers(self):
        trackers = '''http://btfans.3322.org:8080/announce
http://tracker.lzbt.net:8077/announce
http://tracker.prq.to/announce
http://www.pcttracker.com:2710/announce
http://bt1.btbbt.com:7000/announce
http://bt.cnxp.com:8080/announce
http://bt.cnxp.com:6969/announce
http://bt.eastgame.net:82/announce'''
        t = Torrent(self.tf)
        t.add_trackers(trackers)
        t.dump()
        t = Torrent(self.tf)
        assert len(t.schema['announce-list']) == 8
        
    def tearDown(self):
#         os.remove(self.tf)
        pass
        
    
    